package codepulse.blogmoon.cn.system.service.impl;

import codepulse.blogmoon.cn.common.utils.BaseConvert;
import codepulse.blogmoon.cn.system.dto.SysMenuTreeDTO;
import codepulse.blogmoon.cn.system.dto.admin.SysAdminMenuTreeDTO;
import codepulse.blogmoon.cn.system.entity.SysAdminMenu;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import codepulse.blogmoon.cn.system.entity.SysMenu;
import codepulse.blogmoon.cn.system.service.SysMenuService;
import codepulse.blogmoon.cn.system.mapper.SysMenuMapper;
import org.apache.commons.collections.CollectionUtils;
import org.assertj.core.util.Lists;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 61748
 * @description 针对表【sys_menu(系统-菜单表)】的数据库操作Service实现
 * @createDate 2024-01-12 14:05:56
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
        implements SysMenuService {


    @Override
    public List<SysMenuTreeDTO> getAllMenuTree() {
        List<SysMenu> menuList = list();
        return convertTree(menuList);
    }

    @Override
    public List<SysMenuTreeDTO> getMenuTree(Long bizAcctId) {
        List<SysMenu> menuList = list();
        return convertTree(menuList);
    }


    private List<SysMenuTreeDTO> convertTree(List<SysMenu> menus) {
        if (CollectionUtils.isEmpty(menus)) {
            return Lists.newArrayList();
        }
        List<SysMenuTreeDTO> rootList = Lists.newArrayList();
        Map<Long, SysMenuTreeDTO> menuTreeMap = menus.stream().collect(Collectors.toMap(SysMenu::getId,
                item -> BaseConvert.convert(item, SysMenuTreeDTO.class)));
        for (SysMenuTreeDTO adminMenuTreeDTO : menuTreeMap.values()) {
            if (Objects.isNull(adminMenuTreeDTO.getParentId()) || Objects.equals(0L, adminMenuTreeDTO.getParentId())) {
                rootList.add(adminMenuTreeDTO);
                continue;
            }
            SysMenuTreeDTO sysAdminMenuTreeDTO = menuTreeMap.get(adminMenuTreeDTO.getParentId());
            if (Objects.isNull(sysAdminMenuTreeDTO)) {
                rootList.add(adminMenuTreeDTO);
                continue;
            }
            if (Objects.isNull(sysAdminMenuTreeDTO.getChildren())) {
                sysAdminMenuTreeDTO.setChildren(Lists.newArrayList());
            }
            sysAdminMenuTreeDTO.getChildren().add(adminMenuTreeDTO);
            sysAdminMenuTreeDTO.getChildren().sort(Comparator.comparing(SysMenuTreeDTO::getSort));
        }
        rootList.sort(Comparator.comparing(SysMenuTreeDTO::getSort));
        return rootList;
    }

}




